package com.wingstudio.springcloud.redis;

import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.params.SetParams;

import java.util.Collections;

@Service
public class RedisService {
    @Autowired
    JedisPool jedisPool;

    /**
     * 锁键成功返回值
     * */
    private static final Long RELEASE_SUCCESS = 1L;

    /**
     * 加锁成功返回值
     * */
    private static final String LOCK_SUCCESS = "OK";
    /**
     * 锁过期时间
     * */
    protected long internalLockLeaseTime = 10000;

    /**
     * 获取锁的超时时间
     * */
    private long timeout = 1000;

    /**
     * 加锁
     * @param prefix 业务名
     * @param id  数据在数据库中的主键
     * @return
     */
    public boolean lock(String prefix,String id,String value, long lockTime){
        Jedis jedis = null;
        Long start = System.currentTimeMillis();
        try{
            jedis = jedisPool.getResource();
            String realKey = prefix + ":" + id;
            //设置set命令的参数
            SetParams params = SetParams.setParams().nx().px(lockTime * 1000);
            for(;;){
//               SET命令返回OK ，则证明获取锁成功
                String result = jedis.set(realKey, value, params);
                if(LOCK_SUCCESS.equals(result)){
                    return true;
                }
                //否则循环等待，在timeout时间内仍未获取到锁，则获取失败
                long l = System.currentTimeMillis() - start;
                if (l>=timeout) {
                    return false;
                }
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }finally {
            jedis.close();
        }
    }

    /**
     * 加锁 默认过期时间10s
     * @param prefix 业务名
     * @param id  数据在数据库中的主键
     * @return
     */
    public boolean lock(String prefix,String id,String value){
        Jedis jedis = null;
        Long start = System.currentTimeMillis();
        try{
            jedis = jedisPool.getResource();
            String realKey = prefix + ":" + id;
            //设置set命令的参数
            SetParams params = SetParams.setParams().nx().px(internalLockLeaseTime);
            for(;;){
//               SET命令返回OK ，则证明获取锁成功
                String result = jedis.set(realKey, value, params);
                if(LOCK_SUCCESS.equals(result)){
                    return true;
                }
                //否则循环等待，在timeout时间内仍未获取到锁，则获取失败
                long l = System.currentTimeMillis() - start;
                if (l>=timeout) {
                    return false;
                }
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }finally {
            jedis.close();
        }
    }

    /**
     * 释放分布式锁
     * @param id 锁的id
     * @param requestId 请求标识
     * @return 是否释放成功
     */
    public boolean releaseDistributedLock(String prefix,String id, String requestId) {
        Jedis jedis = null;
        //使参数KEYS[1]赋值为lockKey，ARGV[1]赋值为requestId。eval()方法是将Lua代码交给Redis服务端执行。Lua脚本
        String script =
                "if redis.call('get',KEYS[1]) == ARGV[1] then" +
                        "   return redis.call('del',KEYS[1]) " +
                        "else" +
                        "   return 0 " +
                        "end";
        try {
            jedis = jedisPool.getResource();
            String realKey = prefix + ":" + id;
            Object result = jedis.eval(script, Collections.singletonList(realKey),
                    Collections.singletonList(requestId));
            if(RELEASE_SUCCESS.equals(result.toString())){
                return true;
            }
            return false;
        }finally {
            jedis.close();
        }
    }


    /**
     *获取当个对象
     * */
    public <T> T get(KeyPrefix prefix,String key,Class<T> clazz){
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            //生成真正的Key
            String realKey = prefix.getPrefix() + key;
            String string = jedis.get(realKey);
            T t = StringToBean(string,clazz);
            return t;
        }finally {
            returnToPool(jedis);
        }
    }

    /**
     * 设置对象
     * */
    public <T> boolean set(KeyPrefix prefix,String key,T value){
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            String string = beanToString(value);
            if(string == null||string.length() <= 0){
                return false;
            }
            //生成真正的Key
            String realKey = prefix.getPrefix() + key;
            int seconds = prefix.expireSeconds();
            if(seconds <= 0) {
                jedis.set(realKey,string);
            }else {
                jedis.setex(realKey,seconds,string);
            }
            return true;
        }finally {
            returnToPool(jedis);
        }
    }
    /**
     * 判断key是否存在
     * */
    public <T> boolean exist(KeyPrefix prefix,String key){
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            //生成真正的Key
            String realKey = prefix.getPrefix() + key;
            return jedis.exists(realKey);
        }finally {
            returnToPool(jedis);
        }
    }
    /**
     * 增加值
     * */
    public <T> Long incr(KeyPrefix prefix,String key){
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            //生成真正的Key
            String realKey = prefix.getPrefix() + key;
            return jedis.incr(realKey);
        }finally {
            returnToPool(jedis);
        }
    }

    /**
     * 减少值
     * */
    public <T> Long decr(KeyPrefix prefix,String key){
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            //生成真正的Key
            String realKey = prefix.getPrefix() + key;
            return jedis.decr(realKey);
        }finally {
            returnToPool(jedis);
        }
    }
    /**
     * 删除
     * */
    public boolean delete(KeyPrefix prefix,String key){
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            //生成真正的key
            String realKey = prefix.getPrefix() + key;
            long ret = jedis.del(realKey);
            return ret > 0;
        }finally {
            returnToPool(jedis);
        }
    }

    public static  <T> String beanToString(T value) {
        if(value == null) {
            return null;
        }
        Class<?> clazz = value.getClass();
        if(clazz == int.class||clazz == Integer.class){
            return ""+value;
        }else if(clazz == String.class){
            return (String)value;
        }else if(clazz == long.class||clazz == Long.class){
            return ""+value;
        }else {
            //此处认为其他类型为Bean类型
            return JSON.toJSONString(value);
        }
    }


    @SuppressWarnings("unchecked") //@SuppressWarnings不让方法出警告
    public static  <T> T StringToBean(String string, Class<T> clazz) {
        if(string == null||string.length() <= 0||clazz == null){
            return null;
        }
        if(clazz == int.class||clazz == Integer.class){
            return (T)Integer.valueOf(string);
        }else if(clazz == String.class){
            return (T)string;
        }else if(clazz == long.class||clazz == Long.class){
            return (T)Long.valueOf(string);
        }else {
            return JSON.toJavaObject(JSON.parseObject(string),clazz);
        }
    }


    private void returnToPool(Jedis jedis){
        if(jedis != null){
            jedis.close();
        }
    }

}
